<template>
  <div class="login-wrapper">
    <div class="login-box">
      <img src="@/assets/logo.png" alt="Logo" class="logo-image" />
      <h2 style="margin:0px">注册账号</h2>
      <el-form :model="registerForm" :rules="rules" ref="registerForm">
        <el-form-item prop="username">
          <el-input v-model="registerForm.username" placeholder="请输入用户名" class="input" />
        </el-form-item>
        <el-form-item prop="password">
          <el-input v-model="registerForm.password" type="password" placeholder="请输入密码" class="input" />
        </el-form-item>
        <el-form-item prop="passwordConfirm">
          <el-input v-model="registerForm.passwordConfirm" type="password" placeholder="请确认密码" class="input" />
        </el-form-item>
        <el-form-item prop="phone">
          <el-input v-model="registerForm.phone" placeholder="请输入手机号" class="input" />
        </el-form-item>
        <el-form-item prop="code">
          <div style="display: flex; gap: 10px">
            <el-input v-model="registerForm.code" placeholder="验证码" class="input" style="flex: 1" />
            <el-button :disabled="codeTimer > 0" @click="sendCode" :loading="sendingCode">
              {{ codeTimer > 0 ? codeTimer + 's' : '发送验证码' }}
            </el-button>
          </div>
        </el-form-item>
        <el-button type="primary" class="login-button" @click="handleRegister" :loading="registering">注册</el-button>
      </el-form>
      <div class="login-link">
        <!-- <el-link type="primary" @click="$router.push('/login')">已有账号？去登录</el-link> -->
      </div>
    </div>
  </div>
</template>

<script>
import md5 from 'js-md5';
import request from '@/utils'

export default {
  name: 'RegisterPage',
  inject: ['openLogin_dialog'],
  data() {
    const validatePasswordConfirm = (rule, value, callback) => {
      if (value !== this.registerForm.password) {
        callback(new Error('两次输入的密码不一致'));
      } else {
        callback();
      }
    };

    const validatePhone = (rule, value, callback) => {
      if (!/^1[3-9]\d{9}$/.test(value)) {
        callback(new Error('请输入正确的手机号'));
      } else {
        callback();
      }
    };

    return {
      registerForm: {
        username: '',
        password: '',
        passwordConfirm: '',
        phone: '',
        code: ''
      },
      rules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
        ],
        passwordConfirm: [
          { required: true, message: '请确认密码', trigger: 'blur' },
          { validator: validatePasswordConfirm, trigger: 'blur' }
        ],
        phone: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: validatePhone, trigger: 'blur' }
        ],
        code: [
          { required: true, message: '请输入验证码', trigger: 'blur' },
          { len: 6, message: '验证码长度为6位', trigger: 'blur' }
        ]
      },
      codeTimer: 0,
      timer: null,
      sendingCode: false,
      registering: false
    };
  },
  methods: {
    async sendCode() {
      try {
        await this.$refs.registerForm.validateField('phone');

        this.sendingCode = true;
        const response = await request.post(`/login/send_message`, {
          phone: this.registerForm.phone
        });

        if (response.data.code === 200) {
          this.$message.success('验证码发送成功');
          this.startCodeTimer();
        } else {
          this.$message.error(response.msg || '验证码发送失败');
        }
      } catch (error) {
        console.error('发送验证码失败:', error);
        if (error !== '手机号验证失败') {
          this.$message.error('验证码发送失败，请稍后重试');
        }
      } finally {
        this.sendingCode = false;
      }
    },
    startCodeTimer() {
      this.codeTimer = 60;
      this.timer = setInterval(() => {
        this.codeTimer--;
        if (this.codeTimer === 0) {
          clearInterval(this.timer);
        }
      }, 1000);
    },
    async handleRegister() {
      try {
        const valid = await this.$refs.registerForm.validate();
        if (!valid) return;

        this.registering = true;

        const params = {
          username: this.registerForm.username,
          password: md5(this.registerForm.password),
          password_confirm: md5(this.registerForm.passwordConfirm),
          phone: this.registerForm.phone,
          code: this.registerForm.code
        };

        const response = await request.post('/login/register', params);

        if (response.data.code === 200) {
          this.$message.success('注册成功');
		  this.$router.push('/purches')
		  this.openLogin_dialog()
        } else {
          this.$message.error(response.data.msg || '注册失败');
        }
      } catch (error) {
        console.error('注册失败:', error);
        this.$message.error('注册失败，请稍后重试');
      } finally {
        this.registering = false;
      }
    }
  },
  beforeUnmount() {
    if (this.timer) clearInterval(this.timer);
  }
};
</script>

<style scoped>
/* 复用登录页的样式 */
.login-wrapper {
  position: fixed;
  top: 0;
  left: 0;
  width: 100vw;
  height: 100vh;
  backdrop-filter: blur(3px);
  display: flex;
  align-items: center;
  justify-content: center;
}

.login-box {
  width: 400px;
  background: white;
  padding: 30px;
  border-radius: 12px;
  box-shadow: 0 0 12px rgba(0, 0, 0, 0.15);
  text-align: center;
}

.logo-image {
  width: 100px;
  margin-bottom: 16px;
}

.input {
  margin-bottom: 12px;
  width: 100%;
}

.login-button {
  width: 100%;
  margin-top: 10px;
}

.login-link {
  text-align: right;
  margin-top: 10px;
}
</style>